package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.CustomerStoreAdapter;
import com.ramos.kuaixiao.db.CustomerStoreDB;
import com.ramos.kuaixiao.db.SaleCustomerStoreDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.CustomerStore;
import com.ramos.kuaixiao.entity.SaleCustomerStore;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class CustomerStoreActivity extends BaseActivity implements View.OnClickListener {
    private static String TAG = "ShopDetailActivity";
    private Context mContext;
    private LinearLayout title_reback;
    private TextView title_text;
    public final static int UPLOAD_SUCCESS = 1000;
    public final static int UPLOAD_FAIL = 1001;
    RecyclerView mListView;
    Customer mCustomer;
    CustomerStoreAdapter mAdapter;
    LinearLayoutManager mLinearLayoutManager;
    private List<CustomerStore> productList = new ArrayList<>();
    CustomerStoreDB db;
    GeocodeSearch geocoderSearch;
    public final static int REFRESH_SUCCESS = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_store);
        mContext = this;
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        initView();
    }

    private void initView() {
        mCustomer = (Customer) getIntent().getExtras().get("customer");
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("门店列表");

        mListView = (RecyclerView) findViewById(R.id.lv_store);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mListView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new CustomerStoreAdapter(this, productList, mCustomer);
        mListView.setAdapter(mAdapter);
        CustomerStoreDB db = new CustomerStoreDB();
        /*if (!db.hasData()) {
            getCustomerStore(mCustomer.getId());
        } else {*/
        //List<CustomerStore> tmpList = db.findCustomerStore(mCustomer.getQid());
        SaleCustomerStoreDB db1 = new SaleCustomerStoreDB();
        List<SaleCustomerStore> tmpList = db1.findAllCustomerStore(mCustomer.getId());
        if(tmpList.size() > 0){
            List<CustomerStore> tmpList1 = db.findCustomerStore(tmpList);
            if(tmpList1.size() > 0){
                productList.clear();
                productList.addAll(tmpList1);
                mAdapter.notifyDataSetChanged();
                Log.d(TAG, "productList:" + productList.size());
                Product product = new Product(productList);
                product.executeOnExecutor(Executors.newCachedThreadPool());
            } else {
                Intent intent = new Intent(this, ShopDetailActivity.class);

                intent.putExtra("customer", mCustomer);
                startActivity(intent);
                finish();
            }
        }else {
            Intent intent = new Intent(this, ShopDetailActivity.class);

            intent.putExtra("customer", mCustomer);
            startActivity(intent);
            finish();
        }
    }

    class Product extends AsyncTask<String, String, String> {
        private List<CustomerStore> list = new ArrayList<>();

        public Product(List<CustomerStore> type) {
            list = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < list.size(); i++) {

                    final CustomerStore customer = list.get(i);
                    Log.d(TAG, "i:" + i + " " + customer.getAddress() + " : " + customer.getCity());
                    if (!StringUtil.isEmpty(customer.getAddress()) && !StringUtil.isEmpty(customer.getCity())) {
                        geocoderSearch = new GeocodeSearch(mContext);
                        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                            @Override
                            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            }

                            @Override
                            public void onGeocodeSearched(GeocodeResult result, int rCode) {
                                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                                    if (result != null && result.getGeocodeAddressList() != null
                                            && result.getGeocodeAddressList().size() > 0) {
                                        GeocodeAddress address = result.getGeocodeAddressList().get(0);
                                        LatLonPoint latLonPoint = address.getLatLonPoint();
                                        Log.d(TAG, latLonPoint.toString() + " " );
                                        if (latLonPoint != null && !StringUtil.isEmpty(SharedPreference.getPreferString("latitude"))
                                                && !StringUtil.isEmpty(SharedPreference.getPreferString("longitude"))) {
                                            double dis = Utils.getDistance(latLonPoint.getLatitude(), latLonPoint.getLongitude(), Double.valueOf(SharedPreference.getPreferString("latitude")),
                                                    Double.valueOf(SharedPreference.getPreferString("longitude")));
                                            customer.setDistance(String.valueOf(App.df1.format(dis)) + "");
                                            //mAdapter.refresh(productList);
                                            sendMessagea(REFRESH_SUCCESS, list);
                                        }
                                    }
                                }
                            }
                        });
                        GeocodeQuery query = new GeocodeQuery(customer.getAddress(), customer.getCity());// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
                        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Log.d("onGeocodeSearched", "" + productList.size());
            //mAdapter.refresh(productList);
        }
    }

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_SUCCESS:
                    List<CustomerStore> productList = (List<CustomerStore>) msg.obj;
                    mAdapter.refresh(productList);
                    break;
                default:
                    break;
            }
        }
    };

    public void getCustomerStore(String custmerId) {
        try {
            String url = NetUtils.CUSTOMER_STORE_WITH_USER;
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("dealer", SharedPreference.getPreferString("dealer"));
            json.put("custmerId", custmerId);
            String path = url + json.toString();
            Log.d(TAG, "path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result3:  " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            JSONObject jsonObejct3 = JSONObject.parseObject(result);
                            List<CustomerStore> tmpList = JSONArray.parseArray(jsonObejct3.getJSONArray("data").toString(), CustomerStore.class);
                            if (tmpList.size() == 0) {
                                ToastUtils.show("暂无门店数据");
                                Intent intent = new Intent(CustomerStoreActivity.this, ShopDetailActivity.class);
                                intent.putExtra("customer", mCustomer);
                                startActivity(intent);
                            } else {
                                productList.clear();
                                productList.addAll(tmpList);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            default:
                break;
        }
    }
}
